#include "Dispatcher.h"
#include <windows.h>
struct DispatcherAction
{
	void(*func)(void* owner, void* param);
	NetParam* param;
	void* owner;
};

Dispatcher::Dispatcher()
{

}

Dispatcher::~Dispatcher()
{
	WakeAll(true);
}

void Dispatcher::Update()
{
	WakeAll();
}


void Dispatcher::InvokeAsync(void(*func)(void* owner, void* param), void* owner, struct NetParam* param)
{
	dispatchMux.lock();
	DispatcherAction* ac = new DispatcherAction();
	ac->func = func;
	ac->param = param;
	ac->owner = owner;
	funcList.push_back(ac);
	dispatchMux.unlock();
}

void Dispatcher::WakeAll(bool clear)
{
	std::list<DispatcherAction*> acs;
	dispatchMux.lock();
	while (!funcList.empty())
	{
		auto ac = funcList.front();
		acs.push_back(ac);
		funcList.pop_front();
	}
	dispatchMux.unlock();
	while (!acs.empty())
	{
		DispatcherAction* action = acs.front();
		acs.pop_front();
		if (!clear)
			action->func(action->owner, action->param);
		delete (NetParam*)action->param;
		delete action;
	}
}


int64_t GetTimestamp()
{
#if _WIN32
	FILETIME ft;
	int64_t t;
	GetSystemTimeAsFileTime(&ft);
	t = (int64_t)ft.dwHighDateTime << 32 | ft.dwLowDateTime;
	return t / 10 - 11644473600000000;
#else
	struct timeval tv;
	gettimeofday(&tv, NULL);
	return (int64_t)tv.tv_sec * 1000000 + tv.tv_usec;
#endif
}